<template>
  <div>
    <div style="padding: 5px 0">
      <el-input v-model="text" @keyup.enter.native="load" style="width: 200px"> <i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-button @click="add" type="primary" size="mini" style="margin: 10px">新增</el-button>
      <el-button type="success" @click="exportExcel" size="mini" style="margin: 10px">导出</el-button>
    </div>
    <el-table :data="tableData" stripe style="width: 100%" id="out-table">
       
      <el-table-column prop="id" label="ID" width="100" sortable> </el-table-column>
      <el-table-column prop="userImages" label="头像" width="120">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px;border-radius:50px" :src="$store.state.imgURLPre+scope.row.userImages" :preview-src-list="[scope.row.userImages]">
            </el-image>
            </template>
      </el-table-column>
      <el-table-column prop="userUsername" label="用户名"></el-table-column>
      <el-table-column prop="userPassword" label="密码"></el-table-column>
      <el-table-column prop="userPhone" label="手机号"></el-table-column>
      <el-table-column prop="userEmail" label="邮箱"></el-table-column>
      <el-table-column prop="userNickName" label="昵称"></el-table-column>
      <el-table-column prop="userSex" label="性别" >
        <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.userSex==1">男</el-tag>
            <el-tag type="danger" v-else>女</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="userBirthday" label="出生日期">
        <template slot-scope="scope">
          {{scope.row.userBirthday|dataFomart}}
        </template>
      </el-table-column>
      <el-table-column prop="userDescribe" label="描述/签名" ></el-table-column>
      <el-table-column prop="userWallets" label="钱包余额"></el-table-column>
     
      <el-table-column prop="userIdNumber" label="身份证号码"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="90">
        <template slot-scope="scope">
          {{scope.row.createTime|dataFomart2}}
          
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="90">
        <template slot-scope="scope">
          {{scope.row.updateTime | dataFomart2}}
         </template>
      </el-table-column>

      <el-table-column
          fixed="right"
          label="操作"
          width="200">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle  @click="edit(scope.row)"></el-button>
          <el-popconfirm
              @confirm="del(scope.row.id)"
              title="确定删除？"
          >
            <el-button type="danger" icon="el-icon-delete" circle slot="reference" style="margin-left: 10px"></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[2, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 弹窗   -->
    <el-dialog title="信息" :visible.sync="dialogFormVisible" width="30%" lable-width="150px"
               :close-on-click-modal="false">
      <el-form :model="entity" :rules="addFormRules" ref="addFormRef">
       
        <el-form-item label="头像" label-width="150px" prop="userImages">
          <el-upload :action="$store.state.uploadAction" :on-success="fileSuccessUpload" :file-list="fileList"
          list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" label-width="150px" prop="userUsername">
          <el-input v-model="entity.userUsername" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="150px" prop="userPassword">
          <el-input v-model="entity.userPassword" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="150px" prop="userPhone">
          <el-input v-model="entity.userPhone" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="150px" prop="userEmail">
          <el-input v-model="entity.userEmail" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="昵称" label-width="150px" >
          <el-input v-model="entity.userNickName" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="性别" label-width="150px" prop="userSex">
          <el-radio v-model="entity.userSex" label="1">男</el-radio>
          <el-radio v-model="entity.userSex" label="2">女</el-radio>
          <!-- <el-input v-model="entity.userSex" autocomplete="off" style="width: 80%"></el-input> -->
        </el-form-item>
        <el-form-item label="出生日期" label-width="150px" >
          <el-date-picker
          v-model="entity.userBirthday"
          type="date"
          placeholder="选择日期"
          
          >
        </el-date-picker>
          <!-- <el-input v-model="entity.userBirthday" autocomplete="off" style="width: 80%"></el-input> -->
       
        
        </el-form-item>
        <el-form-item label="描述/签名" label-width="150px">
          <el-input  type="textarea" v-model="entity.userDescribe" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
       
     
        <el-form-item label="身份证号码" label-width="150px" prop="userIdNumber">
          <el-input v-model="entity.userIdNumber" autocomplete="off" style="width: 80%"></el-input>
        </el-form-item>
       

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import API from '../../utils/request'
const url = "/api/msslyyUser/"

export default {
  name: "MsslyyUser",
  data() {
    var checkEmail = (rule, value, cb) => {
        const regEamil = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
        if (regEamil.test(value)) {
          return cb()
        }
        cb(new Error('请输入合法的邮箱'))
      }
      var checkMobile = (rule, value, cb) => {
        // 验证手机号的正则表达式
        const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

        if (regMobile.test(value)) {
          return cb()
        }

        cb(new Error('请输入合法的手机号'))
      }
      var checksfz = (rule, value, cb) => {
        // 身份证的正则表达式
        const regsfz = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/

        if (regsfz.test(value)) {
          return cb()
        }

        cb(new Error('请输入正确的身份证号码'))
      }
     
    return {
      fileList: [],
      options: [],
      text: '',
      user: {},
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      entity: {},
      total: 0,
      dialogFormVisible: false,
      addFormRules:{
        userImages:[
        { required: true, message: '请选择头像', trigger: 'blur' }
        ],
        userUsername:[
        { required: true, message: '请输入名称', trigger: 'blur' },
        
       
        ],
      
        userPassword:[
        { required: true, message: '密码', trigger: 'blur' },
        { min: 5,max: 12, message: "密码的长度在5到12之间", trigger: "blur"}  
           
        ],
        userPhone:[
        { required: true, message: '请输入电话', trigger: 'blur' },
        { validator: checkMobile, trigger: 'blur' },
        ],
        userEmail:[
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { validator: checkEmail, trigger: 'blur' },
        ],
        userSex:[
        { required: true, message: '请选择性别', trigger: 'blur' },
      
        ],
       
        userIdNumber:[
        { required: true, message: '身份证号码', trigger: 'blur' },
       
        
        { validator: checksfz, trigger: 'blur' },
        ]
        
      }
    };
  },
  filters:{
     dataFomart(date){
       let dt = new Date(date);//实例化时间对象
       let y = dt.getFullYear();
       let m = dt.getMonth() + 1>10?(dt.getMonth()+ 1):"0"+(dt.getMonth()+ 1);
       let d = dt.getDate()>10?dt.getDate():"0"+dt.getDate(); 
      //笨方法  return y + '-' + m + '-' + d
      //官方方法  注意引号，是tab键上面的符号（ES6的语法）
      return `${y}-${m}-${d}`
    },
    dataFomart2(date){
       let dt = new Date(date);//实例化时间对象
       let y = dt.getFullYear();
       let m = dt.getMonth() + 1>=10?(dt.getMonth()+ 1):"0"+(dt.getMonth()+ 1);
       let d = dt.getDate()>=10?dt.getDate():"0"+dt.getDate(); 
       let hh=dt.getHours()>=10?dt.getHours():"0"+dt.getHours();
       let mm=dt.getMinutes()>=10?dt.getMinutes():"0"+dt.getMinutes();
       let ss=dt.getSeconds()>=10?dt.getSeconds():"0"+dt.getSeconds();
      //笨方法  return y + '-' + m + '-' + d
      //官方方法  注意引号，是tab键上面的符号（ES6的语法）
      return `${y}-${m}-${d}  ${hh}:${mm}:${ss}`
    }
  },
  created() {
    this.user = sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {}
    this.$emit('user', this.user);
    this.load()
  },
  methods: {
    exportExcel () {
   var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
   var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
   try {
    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), this.$options.name+'.xlsx')
   } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
   return wbout
  },
    fileSuccessUpload(res) {
      this.entity.userImages = res.data;
      this.fileList = [res.data]
      console.log(res)
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },
    load() {
       API.get(url + "/page", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            name: this.text
          }
       }).then(res => {
          this.tableData = res.data.records || []
          this.total = res.data.total
       })
    },
    add() {
      this.entity = {}
      this.fileList = []
      this.dialogFormVisible = true
    },
    edit(obj) {
      this.entity = JSON.parse(JSON.stringify(obj))
      this.fileList = []
      this.dialogFormVisible = true
    },
    save() {
      this.$refs.addFormRef.validate(async valid => {
          console.log(valid);
          if (!valid) return
          if (!this.entity.id) {
        API.post(url, this.entity).then(res => {
           if (res.code === '0') {
             this.$message({
               type: "success",
               message: "操作成功"
             })
           } else {
             this.$message({
               type: "error",
               message: res.msg
             })
           }
           this.load()
           this.dialogFormVisible = false
        })
      } else {
        API.put(url, this.entity).then(res => {
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "操作成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load()
          this.dialogFormVisible = false
        })
      }
        })
     
    },
    del(id) {
      API.delete(url + id).then(res => {
        this.$message({
          type: "success",
          message: "操作成功"
        })
        this.load()
       
      })
    }
  },
};
</script>

<style scoped>
 .demo-table-expand {
    font-size: 20px;
  }
  .demo-table-expand label {
    width: 0px;
    color: #49b683;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 100%;
  }
</style>
